package cn.shiwei.hr.service.impl;

import cn.shiwei.hr.domain.Login;
import cn.shiwei.hr.exception.GlobalException;
import cn.shiwei.hr.repository.AssertUtil;
import cn.shiwei.hr.service.ILoginService;
import cn.shiwei.hr.service.IPermissionService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static cn.shiwei.hr.constants.BaseConstants.Login.TYPE_ACCOUNT_BACKSTAGE;

@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private IPermissionService permissionService;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        Login login = loginService.selectOne(wrapper);

        if (login == null) {
            throw new GlobalException("用户不存在");
        }

        // Collection<? extends GrantedAuthority>
        List<GrantedAuthority> list =
                permissionService.selectByLoginId(login.getId()).stream().map(
                        p -> new SimpleGrantedAuthority(p.getSn())
                ).collect(Collectors.toList());

        AssertUtil.isNull(list, "获取权限失败");
        // User(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        UserDetails  user = new User(login.getUsername(), login.getPassword(), login.getEnabled(), login.getAccountNonExpired(), login.getCredentialsNonExpired(),login.getAccountNonLocked(), list);

        return user;
    }
}
